using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Security;
using DTOSW.Service.Membership;
using DTOSW.Core.Membership.Security;
using Newtonsoft.Json;

namespace DTOWS.Controllers
{
    public class ErrorModel
    {
        public string Type { get; set; }
        public string Message { get; set; }
    }
    public class ErrorMessage
    {
        private List<ErrorModel> model;

        public ErrorMessage()
        {
            model = new List<ErrorModel>();
        }

        public void AddErrorMessege(string type, string messege)
        {
            ErrorModel error = new ErrorModel();

            error.Message = messege;
            error.Type = type;

            model.Add(error);

        }
        public List<ErrorModel> ViewErrormessage(string type)
        {
            List<ErrorModel> newErrorModelList = new List<ErrorModel>();

            foreach (ErrorModel error in model) {
                if (error.Type == type) {
                    newErrorModelList.Add(error);
                }
            }

            return newErrorModelList;
        }
        public List<ErrorModel> ViewErrormessage()
        {

            return model;
        }

        public bool IsValid()
        {
            if (model.Count == 0)
                return true;

            return false;
        }
    }

    public class AccountController : Controller
    {
        private ErrorMessage message = new ErrorMessage();


        //
        // GET: /Account/
        MembershipService membership = new MembershipService();
        AuthenticationService authentication = new AuthenticationService();
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult LogOn(string username, string password, bool rememberMe)
        {

            if (!ValidateLogOn(username, password)) {

                return Json(message.ViewErrormessage());
            }

            authentication.SignIn(username, true);

            return Json("Succes");
        }

        public JsonResult SignOut()
        {
            authentication.SignOut();

            return Json("Succes");
        }

        public JsonResult Register(string username, string email, string password, string confirmPassword)
        {

            if (ValidateRegistration(username, email, password, confirmPassword)) {
                CreationStatus creationStatus = membership.CreateUser(username, password, email);

                if (creationStatus == CreationStatus.Success) {
                    authentication.SignIn(username, true);
                    return Json("True");
                }


                ValidateCreationStatus(creationStatus);
                return Json(message.ViewErrormessage());
            }

            return Json(message.ViewErrormessage());
        }
        public JsonResult GetIdentityName()
        {
            return Json(User.Identity.Name);
        }
        public JsonResult IsAuthenticated()
        {
            return Json(User.Identity.IsAuthenticated);
        }



        private bool ValidateLogOn(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName)) {
                message.AddErrorMessege("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(password)) {
                message.AddErrorMessege("password", "You must specify a password.");
            }
            if (!message.IsValid())
                return false;

            UserValidateStatus validateStatus = membership.ValidateUser(userName, password);

            if (validateStatus == UserValidateStatus.InValidPassword) {
                message.AddErrorMessege("_FORM", "The Password is Incorect");
            }
            if (validateStatus == UserValidateStatus.InvalidUserName) {
                message.AddErrorMessege("_FORM", "The username Is Incorect");
            }

            return message.IsValid();
        }

        private bool ValidateRegistration(string userName, string email, string password, string confirmPassword)
        {
            if (String.IsNullOrEmpty(userName)) {
                message.AddErrorMessege("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(email)) {
                message.AddErrorMessege("email", "You must specify an email address.");
            }
            if (!IsValidEmailAddress(email)) {
                message.AddErrorMessege("email", "It's not a valid email");
            }
            if (password == null || password.Length < 6) {
                message.AddErrorMessege("password", "You must specify a password of 6 or more characters.");
            }
            if (!String.Equals(password, confirmPassword, StringComparison.Ordinal)) {
                message.AddErrorMessege("_FORM", "The password and confirmation password do not match.");
            }
            return message.IsValid();
        }

        private void ValidateCreationStatus(CreationStatus creationStatus)
        {
            if (creationStatus == CreationStatus.DuplicateUserName) {
                message.AddErrorMessege("username", "Brugernavnet er uptaget.");
            }

            if (creationStatus == CreationStatus.Failed) {
                message.AddErrorMessege("_FORM", "Der skete en fejl");
            }
        }
        private bool IsValidEmailAddress(string sEmail)
        {
            if (sEmail == null) {
                return false;
            }

            int nFirstAT = sEmail.IndexOf('@');
            int nLastAT = sEmail.LastIndexOf('@');

            if ((nFirstAT > 0) && (nLastAT == nFirstAT) &&
            (nFirstAT < (sEmail.Length - 1))) {
                // address is ok regarding the single @ sign
                return (Regex.IsMatch(sEmail, @"(\w+)@(\w+)\.(\w+)"));
            }


            return false;

        }




        //private static string ErrorCodeToString(UserValidateStatus userValidateStatus)
        //{
        //    // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
        //    // a full list of status codes.
        //    switch (userValidateStatus) {
        //        case UserValidateStatus.UserNotExist:
        //            return "The username Is Incorect";

        //        case UserValidateStatus.PasswordNotMatch:
        //            return "The Password is Incorect";

        //        case UserValidateStatus.Success:
        //            return "The password provided is invalid. Please enter a valid password value.";

        //        case UserValidateStatus.Failed:
        //            return "The e-mail address provided is invalid. Please check the value and try again.";

        //        default:
        //            return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
        //    }
        //}


    }


}
